import { NextRequest, NextResponse } from 'next/server';
import { DocumentOperations } from '@/lib/database-operations';
import { qdrantClient } from '@/lib/db';
import { embeddingModel } from '@/lib/deepseek';

// 向量搜索
async function vectorSearch(
  query: string,
  limit: number = 10,
  threshold: number = 0.7,
  userId?: string
) {
  try {
    // 生成查询向量
    const queryEmbedding = await embeddingModel.embedQuery(query);

    // 构建搜索过滤器
    const filter: any = {};
    if (userId) {
      filter.must = [
        {
          key: 'user_id',
          match: { value: userId },
        },
      ];
    }

    // 在Qdrant中搜索相似向量
    const searchResult = await qdrantClient.search('documents', {
      vector: queryEmbedding,
      limit,
      score_threshold: threshold,
      with_payload: true,
      filter: Object.keys(filter).length > 0 ? filter : undefined,
    });

    return searchResult.map(result => ({
      id: result.id,
      score: result.score || 0,
      content: result.payload?.content || '',
      title: result.payload?.title || '',
      document_id: result.payload?.document_id || '',
      chunk_index: result.payload?.chunk_index || 0,
      metadata: result.payload?.metadata || {},
    }));
  } catch (error) {
    console.error('向量搜索失败:', error);
    return [];
  }
}

// 文本搜索（在文档内容中搜索关键词）
async function textSearch(query: string, limit: number = 10, userId?: string) {
  try {
    const documents = await DocumentOperations.searchByContent(
      query,
      userId,
      limit
    );
    return documents;
  } catch (error) {
    console.error('文本搜索失败:', error);
    return [];
  }
}

// 混合搜索（结合向量搜索和文本搜索）
async function hybridSearch(
  query: string,
  limit: number = 10,
  threshold: number = 0.7,
  userId?: string
) {
  try {
    // 并行执行向量搜索和文本搜索
    const [vectorResults, textResults] = await Promise.all([
      vectorSearch(query, Math.ceil(limit * 0.7), threshold, userId),
      textSearch(query, Math.ceil(limit * 0.3), userId),
    ]);

    // 合并结果并去重
    const combinedResults = new Map();

    // 添加向量搜索结果（权重较高）
    vectorResults.forEach(result => {
      combinedResults.set(result.document_id, {
        ...result,
        search_type: 'vector',
        relevance_score: result.score,
      });
    });

    // 添加文本搜索结果（如果不存在）
    textResults.forEach(result => {
      if (!combinedResults.has(result.id)) {
        combinedResults.set(result.id, {
          id: result.id,
          document_id: result.id,
          title: result.title,
          content: result.content?.substring(0, 500) + '...',
          search_type: 'text',
          relevance_score: 0.5, // 文本搜索默认分数
          metadata: result.metadata || {},
        });
      }
    });

    // 按相关性分数排序
    return Array.from(combinedResults.values())
      .sort((a, b) => b.relevance_score - a.relevance_score)
      .slice(0, limit);
  } catch (error) {
    console.error('混合搜索失败:', error);
    return [];
  }
}

// 搜索API
export async function POST(request: NextRequest) {
  try {
    const {
      query,
      type = 'hybrid',
      limit = 10,
      threshold = 0.7,
      userId,
    } = await request.json();

    if (!query?.trim()) {
      return NextResponse.json(
        { success: false, error: '搜索查询不能为空' },
        { status: 400 }
      );
    }

    let results: any[] = [];

    switch (type) {
      case 'vector':
        results = await vectorSearch(query, limit, threshold, userId);
        break;

      case 'text':
        results = await textSearch(query, limit, userId);
        break;

      case 'hybrid':
      default:
        results = await hybridSearch(query, limit, threshold, userId);
        break;
    }

    return NextResponse.json({
      success: true,
      data: {
        query,
        type,
        results,
        total: results.length,
        limit,
        threshold: type === 'text' ? undefined : threshold,
      },
    });
  } catch (error) {
    console.error('搜索处理失败:', error);
    return NextResponse.json(
      { success: false, error: '搜索处理失败' },
      { status: 500 }
    );
  }
}

// 获取搜索建议
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const query = searchParams.get('q');
    const userId = searchParams.get('userId') || undefined;
    const limit = parseInt(searchParams.get('limit') || '5');

    if (!query?.trim()) {
      return NextResponse.json({
        success: true,
        data: {
          suggestions: [],
        },
      });
    }

    // 获取相关文档标题作为搜索建议
    const documents = await DocumentOperations.searchByTitle(
      query,
      userId,
      limit
    );

    const suggestions = documents.map(doc => ({
      title: doc.title,
      document_id: doc.id,
      snippet: doc.content?.substring(0, 100) + '...',
    }));

    return NextResponse.json({
      success: true,
      data: {
        query,
        suggestions,
      },
    });
  } catch (error) {
    console.error('获取搜索建议失败:', error);
    return NextResponse.json(
      { success: false, error: '获取搜索建议失败' },
      { status: 500 }
    );
  }
}
